import { Global, Injectable, Module } from "@nestjs/common";
import { FastifyRequest } from "fastify";
import IP2Region from "ip2region";
import { UAParser } from "ua-parser-js";

@Injectable()
export class InformationService {
  ipQuery: IP2Region;

  constructor() {
    this.ipQuery = new IP2Region();
  }

  getUAInformation(request: FastifyRequest): { os: string; browser: string } {
    const userAgent = request.headers["user-agent"] || "";
    const platformVersion: any = request.headers["sec-ch-ua-platform-version"];
    const parser = new UAParser(userAgent);
    const uaResult = parser.getResult();
    // console.log(uaResult);

    let osVersion = uaResult.os.version;
    // Windows 11
    if (
      uaResult.os.name === "Windows" &&
      platformVersion &&
      parseInt(platformVersion.substring(1)) >= 13
    ) {
      osVersion = "11";
    }

    const os = `${uaResult.os.name || "未知"} ${osVersion || ""}`;
    const browser = `${uaResult.browser.name || "未知"} ${uaResult.browser.version || ""}`;
    return {
      os,
      browser,
    };
  }

  getIP(request: FastifyRequest): string | undefined {
    const ip: any =
      request.headers["x-real-ip"] ||
      request.headers["x-forwarded-for"] ||
      request.ip ||
      request.socket.remoteAddress ||
      undefined;
    return ip;
  }

  getRegion(ip: string) {
    const ipRegion = this.ipQuery.search(ip);
    // console.log(ipRegion);
    return `${ipRegion.country}${ipRegion.province}${ipRegion.city === "内网IP" ? "" : ipRegion.city}`;
  }
}

@Global()
@Module({
  providers: [InformationService],
  exports: [InformationService],
})
export class InformationModule {}
